<?php

namespace App\Http\Controllers;

use App\Student;
use Illuminate\Http\Request;

use App\Http\Requests;

class studentController extends Controller
{
    //学生列表页
    public function index(){
        $students = Student::paginate(5);
        return view('student.index',['students' => $students]);
    }
    //添加页面
    public function create(){
        return view('student.create');
    }
    //保存添加
    public function save(Request $request){
        $data = $request -> input('student');

        $this->validate($request,[
            'student.name' => 'required|min:2|max:20',
            'student.age' => 'required|integer',
            'student.sex' => 'required|integer',
        ],[
            'required' => ':attribute 为必填项',
            'min' => ':attribute 长度不符合要求',
            'integer' => ':attribute 必须为整数'
        ],[
            'student.name' => '姓名',
            'student.age' => '年龄',
            'student.sex' => '性别',
        ]);
        if(Student::create($data)){
            return redirect('student/index')->with('success','添加成功');
        }else{
            return redirect()->back()->with('error','添加失败');
        }
    }

    //详情页
    public function detail($id){
        $student = Student::find($id);
        return view('student.detail',['student' => $student]);
    }

    //修改页
    public function update(Request $request,$id){
        if($request->has('student')){

            $this->validate($request,[
                'student.name' => 'required|min:2|max:20',
                'student.age' => 'required|integer',
                'student.sex' => 'required|integer',
            ],[
                'required' => ':attribute 为必填项',
                'min' => ':attribute 长度不符合要求',
                'integer' => ':attribute 必须为整数'
            ],[
                'student.name' => '姓名',
                'student.age' => '年龄',
                'student.sex' => '性别',
            ]);

            $student = Student::find($id);
            $data = $request->input('student');
            $student->name = $data['name'];
            $student->age = $data['age'];
            $student->sex = $data['sex'];

            if($student->save()){
                return redirect('student/index')->with('success','修改成功');
            }else{
                return redirect()->back()->with('error','修改失败');
            }
        }
        $student = Student::find($id);
        return view('student.update',['student' => $student]);
    }

    public function delete($id){
        //Student::find($id)->delete();
        if(Student::destroy($id)){
            return redirect('student/index')->with('success','删除成功');
        }else{
            return redirect()->back()->with('error','删除失败');
        }
    }
}
